//#include "serial.h"
#include "boost.h"

using namespace std;

//#define c_mode 1
#define cxx_mode 1

#ifdef c_mode
int main(int argc, char** argv)
{
	int iRet;
	int fd = -1;
	char buffer[128];
	uint8_t recv_data[799];
	ssize_t bytes_read;
	int total_num = 799;

	if (argc != 2)
	{
		printf("Usage: \n");
		printf("%s </dev/ttySAC1 or other>\n", argv[0]);
		return -1;
	}

	fd = open_port(argv[1]);
	if (fd < 0)
	{
		printf("open port err!\n");
		return -1;
	}

	iRet = setup_serial(fd, 115200, 8, 'N', 1);
	if (iRet)
	{
		printf("set port err!\n");
		return -1;
	}
   
	while (1) {
		//bytes_read = read(fd, buffer, sizeof(buffer) - 1);
		//num += bytes_read;
		//if (bytes_read > 0) {
		//	buffer[bytes_read] = '\0';
		//	printf("Received len=%d \ndata=\n", bytes_read);  // %s
		//	//for(int i = 0; i < bytes_read; i++){
		//	//	printf("%x ", buffer[i]);
		//	//}
		//	printf("\n");
		//	fflush(stdout);
		//}
		//else if (bytes_read == -1 && errno == EAGAIN) {
		//	continue;
		//}
		//else {
		//	perror("read failed");
		//	exit(-1);
		//}

		bytes_read = serial_recv(fd, recv_data, 799);
		NMEA nmea;
		memset(nmea, 0, sizeof(nmea));
		if (bytes_read == total_num)
			analysis_data(bytes_read, recv_data, &nmea);
		else
			printf("recv_data len is error!\n");

		printf("received the total data is %d\n", bytes_read);
		//write(fd, cmd, strlen(cmd));
	}
	close(fd);
	return 0;
}
#endif

#ifdef cxx_mode
int main() {
	try {
		system("sudo chmod 777 /dev/ttyS5");

		char serial_dev[32] = "/dev/ttyS5";
		int band_rate = 9600;
		int data_size = 8;
		std::string data;
		NMEA nmea;
		memset(&nmea, 0, sizeof(NMEA));

		nmea_serial nmea_s;
		boost::asio::serial_port serial = nmea_s.init(serial_dev, band_rate, data_size);

		for (;;) {
			// 读取串口数据
			char rdbuf[108];
			size_t len = serial.read_some(buffer(rdbuf, 108));
			data.append(rdbuf, len);

			// 检查是否收到完整的行
			size_t pos = data.find('\n');
			if (pos != std::string::npos) {
				std::string line = data.substr(0, pos);
				data.erase(0, pos + 1); // 移除已处理的行

				nmea_s.analysis_data(line, nmea);
			}
		}
	}
	catch (std::exception& e) {
		std::cerr << e.what() << std::endl;
	}

	return 0;
}
#endif
